package net.gazhi.delonix.core.util;

import org.springframework.util.StringUtils;

public class IPUtils {

	/**
	 * 把IP从字符串转化成【网络序】数字格式
	 * 
	 * @param ip
	 * @return 返回 -1 表示转换失败
	 */
	public static final long parse(String ip) {
		try {
			String[] arr = StringUtils.delimitedListToStringArray(ip, ".");
			return (Long.parseLong(arr[0]) << 24) + (Long.parseLong(arr[1]) << 16) + (Long.parseLong(arr[2]) << 8) + (Long.parseLong(arr[3]));
		} catch (Exception e) {
		}
		return -1;
	}

	/**
	 * 把【网络序】数字IP格式为字符串
	 * 
	 * @param ip
	 * @return
	 */
	public static final String format(long ip) {
		String[] arr = new String[4];
		arr[0] = String.valueOf((ip & 0xFF000000L) >> 24);
		arr[1] = String.valueOf((ip & 0x00FF0000L) >> 16);
		arr[2] = String.valueOf((ip & 0x0000FF00L) >> 8);
		arr[3] = String.valueOf((ip & 0x000000FFL));
		return StringUtils.arrayToDelimitedString(arr, ".");
	}

	/**
	 * 网络序与主机序互转
	 * 
	 * @param ip
	 * @return
	 */
	public static final long reverse(long ip) {
		long[] arr = new long[4];
		arr[0] = (ip & 0xFF000000L) >> 24;
		arr[1] = (ip & 0x00FF0000L) >> 16;
		arr[2] = (ip & 0x0000FF00L) >> 8;
		arr[3] = (ip & 0x000000FFL);
		return (arr[3] << 24) + (arr[2] << 16) + (arr[1] << 8) + arr[0];
	}

	public static void main(String[] args) {

		System.out.println("192.168.1.153 网络序 >> " + parse("192.168.1.153"));
		System.out.println("3232235929L 网络序 >> " + format(3232235929L));

		System.out.println();

		System.out.println("3232235929L 网络序转主机序 >> " + reverse(3232235929L));
		System.out.println("2567022784L 主机序转网络序 >> " + reverse(2567022784L));

		System.out.println();
		System.out.println("网络序输出： " + format(3232236055L));
		System.out.println("转为主机序后仍按网络序输出：" + format(reverse(3232236055L)));

	}

}
